package com.healthcloud.controller;

import com.healthcloud.entity.AreaCode;
import com.healthcloud.entity.LargeArea;
import com.healthcloud.service.AreaCodeService;
import com.healthcloud.service.LargeAreaService;
import com.healthcloud.utils.ApiRes;
import com.healthcloud.utils.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>区域编码控制器</p>
 * <p/>
 * Created by xiam on 2015/6/8.
 */
@ApiIgnore
@Controller
@RequestMapping(value = "/area")
public class AreaMgmtController {

    @Autowired
    private AreaCodeService areaCodeService;

    @Autowired
    private LargeAreaService largeAreaService;

    /**
     * 大区管理列表页面
     * */
    @RequestMapping(value = "/toSearch")
    public String toSearchArea(Model model) {
        List<AreaCode> provinceList = areaCodeService.getProvinceList();
        model.addAttribute("provinceList", provinceList);//省级列表
        return "base/area/search_area";
    }

    /**
     * 大区管理列表页面
     * */
    @RequestMapping(value = "/search")
    public @ResponseBody
    Map<String, Object> searchArea(AreaCode area,Model model, @ModelAttribute("pageParam")PageParam pageParam){
        List<AreaCode> areaCodeList = areaCodeService.search(area, pageParam);
        ArrayList<AreaCode> areaCodeAllList = areaCodeService.searchAll();
//        int count = areaCodeService.count(area);
        int count = areaCodeAllList.size();
        Map<String, Object> map = new HashMap();
        map.put("allData",areaCodeAllList);
        map.put("dataList",areaCodeList);
        map.put("iTotalRecords",count);
        map.put("iTotalDisplayRecords", count);
        map.put("sEcho", pageParam.getsEcho());
        return map;
    }

    /**
     * 大区增加界面
     * */
    @RequestMapping(value = "/toAdd")
    public String toAddLargeArea(Model model) {
        return "base/area/add_area";
    }

    /**
     * 新增大区数据
     * */
    @RequestMapping(value = "/add")
    public @ResponseBody
    ApiRes addLargeArea(LargeArea largeArea, Model model) {
        Integer number=1;
//        ArrayList<AreaCode> areaCodeAllList = areaCodeService.searchAll();
        ArrayList<LargeArea> largeAreas = (ArrayList<LargeArea>) largeAreaService.findByEntityAll(new LargeArea());
        if(largeAreas.isEmpty()){
            number=1;
        }else{
            for (int i = 0; i < largeAreas.size(); i++) {
                if (number<Integer.valueOf(largeAreas.get(i).getLargeAreaCode())){
                    number=Integer.valueOf(largeAreas.get(i).getLargeAreaCode());
                }
            }
            number ++;
        }
        largeArea.setLargeAreaCode(number.toString());
        largeAreaService.save(largeArea);
        return new ApiRes(true,null,null,null);
    }

    /**
     * 大区修改界面
     * */
    @RequestMapping(value = "/toUpdate")
    public String toUpdateLargeArea(String largeAreaCode, Model model) {
        LargeArea largeArea = largeAreaService.get(largeAreaCode);
        model.addAttribute("largeArea", largeArea);
        return "base/area/update_area";
    }

    /**
     * 根据id更新大区数据，并更新地区省级数据
     * */
    @RequestMapping(value = "/update")
    public @ResponseBody
    ApiRes updateLargeArea(LargeArea largeArea, String largeAreaCodeOld, Model model) {
        largeArea.setLargeAreaCode(largeAreaCodeOld);
        largeAreaService.update(largeArea, largeAreaCodeOld);
        return new ApiRes(true,null,null,null);
    }

    /**
     * 根据id批量删除大区数据，并批量更新地区省级数据
     * */
    @RequestMapping(value = "/deletes")
    public @ResponseBody
    ApiRes deleteLargeAreas(String ids, Model model) {
        String[] largeAreaCodes = ids.split(",");
        largeAreaService.deletes(largeAreaCodes);
        return new ApiRes(true,null,null,null);
    }

    /**
     * 根据id修改地区所管理的大区信息
     * */
    @RequestMapping(value = "/updateAreaLargeAreaCode")
    public @ResponseBody
    ApiRes updateAreaLargeAreaCode(String id, String largeAreaCode, Model model) {
        areaCodeService.updateLargeAreaCodeById(id, largeAreaCode);
        return new ApiRes(true,null,null,null);
    }

    /**
     * 修改大区所管理的辖区信息
     * largeAreaCode：大区code
     * ids：辖区id
     * */
    @RequestMapping(value = "/popedomUpdate")
    public @ResponseBody
    ApiRes popedomUpdate(String largeAreaCode, String ids, Model model) {
        if(ids==null){
            areaCodeService.setLargeAreaCodeNull(largeAreaCode);
        }else{
            areaCodeService.setLargeAreaCodeNull(largeAreaCode);
            String[] idArr = ids.split(",");
            for (int i = 0; i < idArr.length; i++) {
                areaCodeService.updateLargeAreaCodeById(idArr[i],largeAreaCode);
            }
        }

        return new ApiRes(true,null,null,null);
    }

    //-----------------------------------------------------------------------------------------------------------------

    /**
     * 根据code，level获取下级地区列表
     */
    @RequestMapping(value = "/getLowerAreaList")
    public @ResponseBody List<AreaCode> getLowerAreaList(HttpServletResponse response,String code, String level) {
        List<AreaCode> areaCodeList = areaCodeService.getLowerAreaList(code, level);
//        try {
//            response.getWriter().write(JSONArray.fromObject(areaCodeList).toString());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return areaCodeList;
    }

    /**
     * 验证largeAreaCode是否存在
     *
     * @param largeAreaCode:要验证的大区编码
     * @param exception:修改时，原来的大区编码
     * @reurn true:验证通过 不存在largeAreaCode
     */
    @RequestMapping(value = "/validateLargeAreaCode")
    public @ResponseBody Object validateLargeAreaCode(String largeAreaCode, String exception) {
        Map<String,Boolean> map = new HashMap<>();
        if(largeAreaCode!=null && exception!=null && largeAreaCode.trim().equals(exception.trim())){
            map.put("valid",true);
            return map;
        }
        if(largeAreaCode==null||"".equals(largeAreaCode.trim())){
            map.put("valid",false);
            return map;
        }
        LargeArea largeArea = largeAreaService.get(largeAreaCode);
        if (largeArea == null) {
            map.put("valid",true);
            return map;
        } else {
            map.put("valid",false);
            return map;
        }
    }

    /**
     * 验证largeAreaName是否存在
     *
     * @reurn true:验证通过 不存在largeAreaName
     */
    @RequestMapping(value = "/validateLargeAreaName")
    public boolean validateLargeAreaName(String largeAreaName, String exception) {
        LargeArea largeArea = largeAreaService.getByLargeAreaName(largeAreaName);
        if (largeArea == null || (exception!=null && largeArea.getLargeAreaName().equals(exception.trim()))) {
            return true;
        } else {
            return false;
        }
    }

}
